<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Proyect Info</title>
<link rel="icon" href="resources/img/favicon.png" type="image/x-icon" />
	<script src="resources/frontResources/jquery/js/jquery-1.9.1.js"></script>
	<script src="resources/frontResources/bootstrap-3.0.2/js/bootstrap.min.js"></script>
	<link rel="stylesheet" href="resources/frontResources/bootstrap-3.0.2/css/jumbotron.css">
	<link rel="stylesheet" href="resources/frontResources/bootstrap-3.0.2/css/bootstrap.min.css">
	<link rel="stylesheet" href="resources/frontResources/tableSorter/css/theme.bootstrap.css">
	<!--Include Open Layer-->
	<script src="http://openlayers.org/api/2.13.1/OpenLayers.js" type="text/javascript"></script>    
	<script src="http://maps.google.com/maps/api/js?v=3&amp;sensor=false"></script>
	<script src="resources/frontResources/Json/json2.js"></script>
	<script src="resources/js/componentesForm.js" type="text/javascript"></script>
</head>
<body>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<div class="navbar navbar-inverse navbar-fixed-top"><!-- Barra de navegacion supeior -->
	<div class="container">
		<a class="navbar-brand" href="${ctx}/projecDetail.htm">MyGIS [<b>Panel de Control</b>]</a>
 			<div style="float: right;"> 
				<img style="vertical-align: middle;"src="<%=request.getContextPath()%>/resources/img/avatar.png"/>
					<button type="button" class="btn btn-warning" onclick="window.location = '<%=request.getContextPath()%>/loguin.htm'">${user.userName} / Sign Out</button>
 			</div> 
	</div>
</div>
		<div style="width:100%; height:100%; float: right;" id="map"></div>
		<input type="hidden" id="externalLayerContent" value='${externalLayer}'/>
		<input type="hidden" id="customLayerContent" value='${customLayer}'/>
		<input type="hidden" id="customLayerContentGIS" value=""/>	
		<input type="hidden" id="latLayer" value='${lat}'/>
		<input type="hidden" id="longLayer" value='${long}'/>
		<input type="hidden" id="zoonLayer" value='12'/>
    </body>
</html>
    <script type="text/javascript">
    	// Inicio definicion de variables globales
    	var map, layerOSM, gmap, vectorLayer,drawPoint, customLayer;
    	var controls; // Esta variable contiene los controles para dibujar feature sobre el mapa (Ver panel a la izquierda del mapa). 
		var layers = new Array(); 
		var layersName = new Array(); 
		var type = "kml";
		var selectedFeatures = new Array();
		var vectorCustomLayer = new Array();
		var temporalFeature;

		var infoCustomLayer = function (idLayer, customForm, layer) {
			this.idLayer	= idLayer;
			this.customForm = customForm;
			this.layer		= layer;
			this.controls = new Array();
			}

		// Fin definicion de variabler globales
		
		//***********************************************************************************************************************
		//***********************************************************************************************************************
		// Este es el inicio, se crea el mapa y se setea la capa base, luego se crean las capas externas, por ultimos se agregan 
		// las capas custom con su correspondientes controles.
		//***********************************************************************************************************************
		//***********************************************************************************************************************
		$( document ).ready(function() {

			//Esta funcion se encarga de crear el mapa donde seran dibujadas las capas. Esto toma una latitud,longitud y zoon inicial.
			loadBasicsLayers($("#latLayer").val(),$("#longLayer").val(),$("#zoonLayer").val());
			
			//En este punto se recupera la informacion correspondiente a las capas externas y se procede a crear y dibujar las mismas sobre un layer.
			var listExternalLayer = $("#externalLayerContent").val();// En este hidden se setea en formato JSon la informacion de layers tipo external.
			var objectListExternalLayer = jQuery.parseJSON(listExternalLayer);
			for (var i=0; i < objectListExternalLayer.length; i++){
		        var item = objectListExternalLayer[i];
		        loadKmlLayer(item.nameLayerkey,item.layerKml);
		    }
			
			//En este punto se recupera la informacion correspondiente a las capas custom y se procede a parsear las mismas y a plasmace sobre un layer.
			var listCustomLayer = $("#customLayerContent").val();// En este hidden se setea en formato JSon la informacion de layers tipo custom
			var objectListCustomLayer = jQuery.parseJSON(listCustomLayer);
			for(var j=0; j < objectListCustomLayer.length;j++){
	    		var customLayerInformation = objectListCustomLayer[j].layerCustom;
	    		var wkt = new OpenLayers.Format.WKT();
				
	    		var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
	            renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;
	            
	           	//Con lo siguiente se define un estilo para la capa, en este caso tambien se setea el marcardo.
	            var style = new OpenLayers.StyleMap({
	                pointRadius: 15, // based on feature.attributes.type
	                //fillColor: "#666666"
	                externalGraphic : "resources/img/markers/"+objectListCustomLayer[j].marker+".png"
	            });
	           	
	            customLayer = new OpenLayers.Layer.Vector(objectListCustomLayer[j].nameLayerkey,{
	                styleMap:style,
	                renderers: renderer
	            });
	            
	            //Se itera el conjunto de marcadores, se transforman a wkt y se insertan en un layer.
	    		for (var i=0; i < customLayerInformation.length; i++){
		        	var item = customLayerInformation[i];
		        	//Dado que en el controlador genero una clave ("tupla"+index |Ej: tupla0, tupla1, tupla2, ... tuplaN) mediante js voy a tener 
		        	//que generar la clave (hardcodeada) para poder recuparar dichos valores jSon (Con tomar la primera ya esta).
		        	var clave = "tupla0";
		        	var geometry = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.fromWKT(item[clave].SpatialObjectGeometry).transform(new OpenLayers.Projection("EPSG:4326")));
					geometry.itemsCustom = item;
					geometry.geometry.transform(map.displayProjection, map.getProjectionObject());  
					customLayer.addFeatures([geometry]);
			    }			
				map.addLayer(customLayer);	
			}	
		});
		
		
		function loadBasicsLayers(longitude,latitude,zoom) {
			map = new OpenLayers.Map('map');
			layerOSM = new OpenLayers.Layer.OSM();
			layerGoogleMap  = new OpenLayers.Layer.Google("Google Streets", {visibility: false});
			
			var fromProjection = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984
			var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
			var initialPosition = new OpenLayers.LonLat(longitude,latitude).transform( fromProjection, toProjection);
	 
			map.addControl(new OpenLayers.Control.LayerSwitcher());

			map.addLayers([layerOSM,layerGoogleMap]);
			map.setCenter(initialPosition,zoom);
        }		
		
		function loadKmlLayer(layer,kml) {
			var vector_options = {
				  units: "m",
				};
			var vectors = new OpenLayers.Layer.Vector(layer, vector_options);		
			map.addLayer(vectors);
			deserialize(kml,vectors);
        }	
		
		// Esta funcion sera llamada desde el document.ready. Lo que hace es asociar la capa custom a openLyers de esta manera cada
		// capa podra colectar la informacion que el usuario ha indicada en su creacion.
		/*function loadCustomLayers(name,customKml,customForm){
			if(customKml==null)
				return 
            var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
            renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;

           	//Con lo siguiente se define un estilo para la capa, en este caso cambio el marcardo.
            var style = new OpenLayers.StyleMap({
                pointRadius: 10, // based on feature.attributes.type
                //fillColor: "#666666"
                externalGraphic : "http://icons2.iconarchive.com/icons/icons-land/vista-map-markers/32/Map-Marker-Marker-Outside-Azure-icon.png"
            });
           	
            customLayer = new OpenLayers.Layer.Vector(name,{
                styleMap:style,
                renderers: renderer
            });
            
            //var info = new infoCustomLayer(customLayer.id,customForm,customLayer);
			//vectorCustomLayer.push(info);
            
			map.addLayer(customLayer);	
			if(customKml!=null)
				renderCustomLayersInformation(customKml);
		}
		
	    function renderCustomLayersInformation(infoLayerCustom){
			//var listCustomLayerGIS = $("#customLayerContentGIS").val();// En este hidden estan toda la informacion GIS
	    	//var customLayerInformation = jQuery.parseJSON(infoLayerCustom);
	    	 var wkt = new OpenLayers.Format.WKT();
			for (var i=0; i < infoLayerCustom.length; i++){
		        var item = infoLayerCustom[i];
		    	//feature.id ="Como miente jose!";
				var point = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.fromWKT(item.spatialObjectGeometry).transform(new OpenLayers.Projection("EPSG:4326")));
				point.id = item.valueFieldNro
				point.geometry.transform(map.displayProjection, map.getProjectionObject());         
				customLayer.addFeatures([point]);
		    }	
	    }*/		
		
		function deserialize(kml,vectors) {
            var in_options = {
              'internalProjection': new OpenLayers.Projection("EPSG:900913"),
              'externalProjection': new OpenLayers.Projection("EPSG:4326")
            };
            var kmlOptionsIn = OpenLayers.Util.extend({ extractStyles: false },in_options);

            var features = new OpenLayers.Format.KML(kmlOptionsIn).read(kml);
            var bounds;

            if (features) {
                if (features.constructor != Array) {
                    features = [features];
                }
                for (var i = 0; i < features.length; ++i) {
                    if (!bounds) {
                        bounds = features[i].geometry.getBounds();
                    } else {
                        bounds.extend(features[i].geometry.getBounds());
                    }
                }
                vectors.addFeatures(features);
                map.zoomToExtent(bounds);
            }
        }   
    </script>